package commands;

import java.util.Vector;

import modLoader.ModLoader;

import cmdclasses.bandit.BanditRunnable;
import cmdclasses.bandit.BanditRunnableImpl;
import cmdclasses.bandit.CurrentPlayed;

import bot.CommandBot;

public class Bandit implements Command {
	Vector<String> targetsToSend;
	java.util.Timer timer;

	public Bandit() {
		targetsToSend = new Vector<String>();
		timer = new java.util.Timer();
	}

	@Override
	public String getCommandName() {
		return "bandit";
	}

	@Override
	public boolean execCommand(String channel, String sender, String login,
			String hostname, String message, CommandBot bot) {
		if (message.equals("")) {
			bot.sendMessage(channel, CurrentPlayed.currentSong());
			return true;
		} else if (message.equals("start")) {
			startPlaying(channel, bot);
			return true;
		} else if (message.equals("stop")) {
			stopSending(channel);
			return true;
		}
		return false;
	}

	private void startPlaying(String channel, CommandBot bot) {
		if (targetsToSend.isEmpty()) {
			BanditRunnableImpl run = (BanditRunnableImpl) ModLoader.newInstance("cmdclasses.bandit.BanditRunnable");
			run.setUp(bot, targetsToSend);
			try {
				timer.cancel();
			}catch(IllegalStateException ie) {
			}
			timer = new java.util.Timer();
			timer.scheduleAtFixedRate(run, 1000 * 5, 1000 * 5);
		}
		if (!targetsToSend.contains(channel)) {
			targetsToSend.add(channel);
			bot.sendMessage(channel, CurrentPlayed.currentSong());
		}
	}

	private void stopSending(String target) {
		targetsToSend.remove(target);
		if (targetsToSend.size() == 0) {
			timer.cancel();
		}
	}

	@Override
	public boolean execCommand(String sender, String login, String hostname,
			String message, CommandBot bot) {
		if (message.equals("")) {
			bot.sendMessage(sender, CurrentPlayed.currentSong());
			return true;
		} else if (message.equals("start")) {
			startPlaying(sender, bot);
			return true;
		} else if (message.equals("stop")) {
			stopSending(sender);
			return true;
		}
		return false;
	}
}
